package edu.whu.demo.controller;

import edu.whu.demo.entity.CommodityItem;
import edu.whu.demo.service.CommodityService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Api(description = "商品管理")
@RestController
@RequestMapping("commodities")
public class CommodityController {
    @Autowired
    CommodityService todoService;

    // get: localhost:8088/commodities/1
    @ApiOperation("根据Id查询商品")
    @GetMapping("/{id}")
    public ResponseEntity<CommodityItem> getTodo(@ApiParam("商品Id")@PathVariable long id){
        CommodityItem result = todoService.getCommodity(id);
        if(result==null) {
            return ResponseEntity.noContent().build();
        }else{
            return ResponseEntity.ok(result);
        }
    }

    // get: localhost:8088/commodities
    // get: localhost:8088/commodities?name=作业
    // get: localhost:8088/commodities?name=作业&&complete=true
    @ApiOperation("根据条件查询商品")
    @GetMapping("")
    public ResponseEntity<List<CommodityItem>> findTodos(@ApiParam("商品名称")String name, @ApiParam("是否完成")Boolean complete){
        List<CommodityItem> result = todoService.findCommodities(name, complete);
        return ResponseEntity.ok(result);
    }

    @ApiOperation("添加商品")
    @PostMapping("")
    public ResponseEntity<CommodityItem> addTodo(@RequestBody CommodityItem todo){
        CommodityItem result = todoService.addCommodity(todo);
        return ResponseEntity.ok(result);
    }

    @ApiOperation("修改商品")
    @PutMapping("/{id}")
    public ResponseEntity<Void> updateTodo(@PathVariable long id,@RequestBody CommodityItem todo){
        todoService.updateCommodity(id,todo);
        return ResponseEntity.ok().build();
    }

    @ApiOperation("删除商品")
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteTodo(@PathVariable long id){
        todoService.deleteCommodity(id);
        return ResponseEntity.ok().build();
    }


    @ApiOperation("上传图片）")
    @PostMapping("/upload")
    public ResponseEntity<String> addTodoWithPic(@RequestParam("file") MultipartFile pic){
        try {
            String picName=UUID.randomUUID()+".jpg";
            File file=new File(picName);
            file.createNewFile();
            pic.transferTo(file);
            return ResponseEntity.ok(picName);
        } catch (IOException e) {
            return ResponseEntity.badRequest().build();
        }
    }


}
